package cn.com.eado.crm.v.fragment


import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.eado.crm.R
import cn.com.eado.crm.app.KEY_USER_ID
import cn.com.eado.crm.app.MyApp
import cn.com.eado.crm.app.extenstion.toast
import cn.com.eado.crm.app.utils.SpUtil
import cn.com.eado.crm.databinding.FragmentAppBinding
import cn.com.eado.crm.m.db.AppIcon
import cn.com.eado.crm.model.LoadStatus
import cn.com.eado.crm.m.db.MyDatabase
import cn.com.eado.crm.v.adapter.RVAppAdapter
import cn.com.eado.preado.app.utils.autoCleared
import cn.com.eado.preado.viewmodel.AppViewModel
import kotlinx.android.synthetic.main.fragment_app.*
import kotlin.concurrent.thread

/**
 * A simple [Fragment] subclass.
 */
class AppFragment : BaseBindingFragment<FragmentAppBinding>(R.layout.fragment_app) {

    private var vm by autoCleared<AppViewModel>()
    private var adapter by autoCleared<RVAppAdapter>()
    private val mList: MutableList<AppIcon> = mutableListOf()

    override fun initTheFragment() {
        initView()
        initViewModel()
        loadData()
    }

    private fun initView() {
        initTitleBar()
        initRecyclerView()
    }

    private fun initTitleBar() {
        titleBar1.tvRightClickCallback = {
//            val bundle = Bundle()
            val userId = SpUtil.readInt(MyApp.instance, KEY_USER_ID, 0)
            val list: MutableList<AppIcon> = mutableListOf()
            for(appIcon in mList){
                if(appIcon.show) {
                    appIcon.id = 0
                    appIcon.userId = userId
                    list.add(appIcon)
                }
            }
//            Log.e("tag", "list=$list")
//            bundle.putParcelableArrayList("list", list as ArrayList<AppIcon>)
//            Navigation.findNavController(view!!).navigate(R.id.action_appFragment_to_homeFragment, bundle)
            thread {
                MyDatabase.getInstance().appIconDao().insertAll(list)
                activity?.runOnUiThread {
                    Navigation.findNavController(view!!).popBackStack()
                }
            }
        }
    }

    private fun initRecyclerView() {
        recyclerView2.layoutManager = LinearLayoutManager(activity)
        val adapter = RVAppAdapter({ view, pos, bean ->  //click
            adapter.notifyItemChanged(pos)
            if (!(bean.name == getString(R.string.customer_manager) ||
                        bean.name == getString(R.string.sales_manager) ||
                        bean.name == getString(R.string.daily_business) ||
                        bean.name == getString(R.string.system_setting)))
            mList[pos].show = !bean.show
//            adapter.refresh(mList)
            })
        recyclerView2.adapter = adapter
        this.adapter = adapter
    }

    private fun initViewModel(){
        vm = ViewModelProviders.of(this).get(AppViewModel::class.java)
        vm.loadResult.observe(this, Observer{
            if (it.status == LoadStatus.SUCCESS){
//                Log.e("tag", "it=$it")
                if (it.data?.isNotEmpty() == true){
                    thread {
                        mList.clear()
//                        val userName = SpUtil.readString(MyApp.instance, KEY_USER_NAME, "unknown")
                        val userId = SpUtil.readInt(MyApp.instance, KEY_USER_ID, 0)
                        for (appIcon in it.data){
                            if(MyDatabase.getInstance().appIconDao().queryShowWithName(true, userId, appIcon.name!!) == null){
                                mList.add(appIcon)
                            }
                        }
                        activity?.runOnUiThread { adapter.refresh(mList) }
                    }
                }
            }else if (it.status == LoadStatus.ERROR){
                activity?.toast(it.message)
            }
        })
    }

    private fun loadData(){
        vm.setLoad(true)
    }

}
